<?php
Class AdminController{
	var $title;
	var $result;
	var $cat;
	var $sub;
	
	public function __construct(){
		LoadHelpers("Use, Pager");
                include_once(LIBRARY_PATH."/Kernel/Access/Acl.php");

	}
	
	public function IndexAction(){
		$this->title = "Перегляд розділів";
		$auth = Df_Auth::read("id");
		
		if(!empty($auth)){
                    $acl = new Df_acl;
                        $acl->SetAclTableName("acl");
                        //Читаем ID групу пользователя
                        $role = Df_Auth::read("role");
                        $acl->addRole($role);
                        $acl->add_Resource("RAZDEL");
                        //Доступ к спискам разделам
                        $acl->add_access("1");
                        $access = array();
                        $access['allow'] = $acl->allow();

						//$access['allow'] = false;
                        if($access['allow'] == true){
                            //Права на создание разделов
                            $acl->add_access("2");
                            $access['allow_write'] = $acl->allow();
                            //Права на редактирование разделов
                            $acl->add_access("3");
                            $access['allow_edit'] = $acl->allow();
                            //Права на публикацию разделов
                            $acl->add_access("4");
                            $access['allow_off'] = $acl->allow();
							//$access['allow_off'] = false;
                            //Права на удаление разделов
                            $acl->add_access("5");
                            $access['allow_delete'] = $acl->allow();
                            //права на смену главной страницы
                            $acl->add_access("6");
                            $access['allow_super'] = $acl->allow();
                            $this->access = $access;
                                $result = ORM::factory('razdel')->Where("uroven", 1)->OrderBy("sort", "ASC")->find_all();

                                if(!empty($result)){
                                        $this->result = $result;
                                }else{
                                        $this->result = array();
                                }
                        }else{
				$this->result = array();
				$this->title = $this->title.". Доступ заборонено!";
			}
		
			$arr = array(array('link'=>'index','name'=>'Головна'));

			$this->link = LinkGen::Link($arr, 'block', 'navig');
		}else{
			header("location: /admin/login.html");
			exit();
		}
	}
	
	public function AddAction(){
		$this->title = "Додати розділ";
		$auth = Df_Auth::read("id");
			if(!empty($auth)){
                            $acl = new Df_acl;
                        $acl->SetAclTableName("acl");
                        //Читаем ID групу пользователя
                        $role = Df_Auth::read("role");
                        $acl->addRole($role);
                        $acl->add_Resource("RAZDEL");
                        //Права на создание разделов
                        $acl->add_access("2");
			$access['allow_write'] = $acl->allow();
                        if($access['allow_write'] == true){

                            //Права на публикацию разделов
                            $acl->add_access("4");
                            $access['allow_off'] = $acl->allow();

                            //права на смену главной страницы
                            $acl->add_access("6");
                            $access['allow_super'] = $acl->allow();
                            $this->access = $access;
				require_once(APPLICATION_PATH."/Models/Razdel.php");
                                $result = Razdel::Add();
                                $this->uroven = $result['uroven'];
                                $this->razdel = $result['razdel'];

                                $this->country = ORM::factory('country')->SetType('object')->find_all();

                        }
		}else{
                    header('location: /admin/logout.html');
		}
	}
	
	public function EditAction(){
            $auth = Df_Auth::read("id");
            if(!empty($auth)){
                $acl = new Df_acl;
                $acl->SetAclTableName("acl");
                //Читаем ID групу пользователя
                $role = Df_Auth::read("role");
                $acl->addRole($role);
                $acl->add_Resource("RAZDEL");
                //Права на редактирование разделов
                $acl->add_access("3");
                $access['allow_edit'] = $acl->allow();
                if($access['allow_edit'] == true){
                    $this->access = $access;
                         require_once(APPLICATION_PATH."/Models/Razdel.php");
                         $result = Razdel::Edit();

                         $this->title = $result['title'];
                         $this->edit_id = $result['id'];
                         $this->edit = $result['edit'];
                }
            }else{
		header('location: /admin/login.html');
            }
	}
	
	public function SetupAction(){
	$auth = Df_Auth::read("id");
	if(!empty($auth)){
                    $acl = new Df_acl;
                    $acl->SetAclTableName("acl");
                    //Читаем ID групу пользователя
                    $role = Df_Auth::read("role");
                    $acl->addRole($role);
                    $acl->add_Resource("RAZDEL");
                    //Права на редактирование разделов
                    $acl->add_access("3");
                    $access['allow_edit'] = $acl->allow();
                    if($access['allow_edit'] == true){
                                            //Права на публикацию разделов
                        $acl->add_access("4");
                        $access['allow_off'] = $acl->allow();

                        //права на смену главной страницы
                        $acl->add_access("6");
                        $access['allow_super'] = $acl->allow();
                        $this->access = $access;
				require_once(APPLICATION_PATH."/Models/Razdel.php");
                                 $result = Razdel::Setup();

                                 $this->title = $result['title'];
                                 $this->edit_id = $result['id'];
                                 $this->edit = $result['edit'];
                      }
            }else{
		header('location: /admin/login.html');
            }
	}
	public function ActionsAction($type=NULL, $params=NULL){
		$auth = Df_Auth::read("id");
		$this->layout = "false";
		if(!empty($auth)){
			$request = getRequest::getInstance();
			$id = $request->getVar('id', 'GET');
			$type = $request->getVar('type', 'GET');
			
			if(!empty($id) && $type=='del_group'){
					ORM::factory()->prepare("DELETE `groups`,`acl` FROM `groups`,`acl` WHERE groups.id=acl.Role AND groups.id='".$id."'")->execute();
			}elseif(!empty($id) && $type=='del_user'){
					ORM::factory()->prepare("DELETE FROM `users` WHERE `id`='".$id."'")->execute();
			}elseif(!empty($id) && $type=='delimg'){
					$files = ORM::factory('gallery')->SetType('assoc')->Select('medi,larg,image')->Where('id',$id)->find_all();
					@unlink(DOCUMENT_ROOT.'/upload/images/gallery/'.$files[0]['medi']);
					@unlink(DOCUMENT_ROOT.'/upload/images/gallery/'.$files[0]['larg']);
					@unlink(DOCUMENT_ROOT.'/upload/images/gallery/'.$files[0]['image']);
					unset($files);
					ORM::factory()->prepare("DELETE FROM `gallery` WHERE `id`='".$id."'")->execute();
			}elseif(!empty($id) && $type=='delgrt'){
					$orm = ORM::factory();
					$orm->prepare("DELETE FROM `GroupTovar`,`CetegoryTovar`,`goods` WHERE GroupTovar.id='".$id."' AND GroupTovar.id=CetegoryTovar.group AND CetegoryTovar.id=goods.Cat")->execute();
					if($orm->IsGood()!=true){
						$orm->prepare("DELETE FROM `GroupTovar`,`CetegoryTovar` WHERE GroupTovar.id='".$id."' AND GroupTovar.id=CetegoryTovar.group")->execute();
						if($orm->IsGood()!=true){
							$orm->prepare("DELETE FROM `GroupTovar` WHERE GroupTovar.id='".$id."'")->execute();
						}
					}
					unset($orm);
			}elseif(!empty($id) && $type=='delct'){
					$orm = ORM::factory();
					$orm->prepare("DELETE FROM `CetegoryTovar`,`goods` WHERE CetegoryTovar.id='".$id."' AND CetegoryTovar.id=goods.Cat")->execute();
					if($orm->IsGood()!=true){
						$orm->prepare("DELETE FROM `CetegoryTovar` WHERE CetegoryTovar.id='".$id."'")->execute();
					}
					unset($orm);
			}elseif(!empty($id) && $type=='delgoods'){
					$files = ORM::factory('goods')->SetType('assoc')->Select('home,image,small,prev')->Where('id',$id)->find_all();
					@unlink(DOCUMENT_ROOT.'/upload/goods/'.$files[0]['home']);
					@unlink(DOCUMENT_ROOT.'/upload/goods/'.$files[0]['image']);
					@unlink(DOCUMENT_ROOT.'/upload/goods/'.$files[0]['small']);
					@unlink(DOCUMENT_ROOT.'/upload/goods/'.$files[0]['prev']);
					unset($files);
					ORM::factory()->prepare("DELETE FROM `goods` WHERE `id`='".$id."'")->execute();
			}elseif(!empty($id) && $type=='deltowns'){
					$orm = ORM::factory();
					$orm->prepare("DELETE FROM `city` WHERE `id`='".$id."'")->execute();
					if($orm->IsGood()!=true){
					$orm->prepare("DELETE FROM `city`,`magazini` WHERE city.id='".$id."' AND city.id=magazini.city")->execute();
					}
					unset($orm);
			}elseif(!empty($id) && $type=='delshops'){
					$orm = ORM::factory();
					$orm->prepare("DELETE FROM `magazini` WHERE `id`='".$id."'")->execute();
					unset($orm);
			}else{
					require_once(APPLICATION_PATH."/Models/Razdel.php");
					Razdel::Operations($type, '', $id);
			}
                    
		}
	}
	
	public function RazdelAction(){

	$auth = Df_Auth::read("id");
	if(!empty($auth)){
            $array = array();
            $acl = new Df_acl;
            $acl->SetAclTableName("acl");
            //Читаем ID групу пользователя
            $role = Df_Auth::read("role");
            $acl->addRole($role);
            $acl->add_Resource("RAZDEL");
            //Доступ к спискам разделам
            $acl->add_access("1");
            $access = array();
            $access['allow'] = $acl->allow();
			//$access['allow'] = false;
              if($access['allow'] == true){
                //Права на создание разделов
                $acl->add_access("2");
                $access['allow_write'] = $acl->allow();
                //Права на редактирование разделов
                $acl->add_access("3");
                $access['allow_edit'] = $acl->allow();
                //Права на публикацию разделов
                $acl->add_access("4");
                $access['allow_off'] = $acl->allow();
				//$access['allow_off'] = false;
                //Права на удаление разделов
                $acl->add_access("5");
                $access['allow_delete'] = $acl->allow();
                //права на смену главной страницы
                $acl->add_access("6");
                $access['allow_super'] = $acl->allow();
                $this->access = $access;
		$request = getRequest::getInstance();
		$id = $request->getVar('id', 'GET');
                
        $this->razdel = $id;
        
        $orm = ORM::factory('razdel', $id)->Select("razdel, uroven, title,type,url")->find_all();
        $this->pag_type = $orm['0']['type'];    
        $razdel = $orm['0']['razdel'];
        $this->url = $orm['0']['url'];
               
		$title = $orm['0']['title'];
        $uroven = $orm['0']['uroven'];
		
		if($this->pag_type==4){
			$count = ORM::factory('goods')->Where("razdel", $id)->OrderBy("sort", "ASC")->_count();
			$this->pager = Pager::Create($count, "/admin/razdel.html?id=".$id."&page=");
			$result = ORM::factory('goods')->SetType('assoc')->Select('id,name,arc,small_cart')->Where("razdel", $id)->OrderBy("sort", "ASC")->Limit($this->pager['limit'])->find_all();
		}else{
			$count = ORM::factory('razdel')->Where("razdel", $id)->OrderBy("sort", "ASC")->_count();
			$this->pager = Pager::Create($count, "/admin/razdel.html?id=".$id."&page=");
			$result = ORM::factory('razdel')->Where("razdel", $id)->OrderBy("sort", "ASC")->Limit($this->pager['limit'])->find_all();
		}		
		if(!empty($result)){
			$this->result = $result;
		}else{
			$this->result = array();
		}
		
		

		$this->title = "Розділ: ".$title;
		unset($orm);
		
		for($i=1; $i<=$uroven; $i++){
                
                    if($i>1){

                        $result = ORM::factory('razdel', $rid)->Select("razdel, title")->Limit("1")->find_all();

                        $param = $rid;
                        
                        if($result[0]['razdel'] == 0){
                             $rid =& $razdel;
                         }else{
                             $rid = $result[0]['razdel'];
                         }

                         $title = $result[0]['title'];
                    }else{
                             $param =& $id;
                             $rid = $razdel;
                    }
			$array[] = array('link'=>"admin/razdel",'name'=>$title,'param'=>$param,'type'=>"id");

                    }
                }

                $array[] = array('link'=>'admin','name'=>'Головна');

                $list = array_reverse($array);
                
		$this->link = LinkGen::Link($list, 'block', 'navig', 1);
            }else{
                header("location: /admin.html");
            }
	}
	public function LoginAction(){
		$this->title = "Авторизація";
		$this->layout = 'false';
		$auth = Df_Auth::read("id");
		if(empty($auth)){
			require_once(APPLICATION_PATH."/Models/User.php");
			$this->login_error = User::Login();
		}else{
			header('location: /admin.html');
		}
	}
	public function LogoutAction(){
		$this->layout = 'false';
		Df_Auth::clear();
		header("location: /admin.html");
		exit();
	}
	
	
	public function FileoperationsAction(){
		$this->layout = "false";
		$auth = Df_Auth::read("id");
			if(!empty($auth)){
               require_once(APPLICATION_PATH."/Models/Media.php");
				Media::Operations();
			}else{
				header('location: /admin.html');
			}
	}
	
	public function MediaAction(){
		$this->title = "Файловий менеджер";
		$auth = Df_Auth::read("id");
		if(!empty($auth)){
                        require_once(APPLICATION_PATH."/Models/Media.php");
                        $manager = Media::Manager();
                            $this->bloks = $manager['result'];
                            $this->allow = $manager['access']['allow'];
                            $this->allow_write = $manager['access']['allow_write'];
                            $this->allow_delete = $manager['access']['allow_delete'];
                            $this->folder = $manager['folder'];
			}else{
				header('location: /admin.html');
			}
	}
	public function CpanelAction(){
		$this->title = "Налаштування";
	}
	public function UsersAction(){
		$this->title = "Користувачі";
		$this->auth = Df_Auth::read("id");
		if(!empty($this->auth)){

                        $acl = new Df_acl;
                        $acl->SetAclTableName("acl");
                        //Читаем ID групу пользователя
                        $role = Df_Auth::read("role");
                        $acl->addRole($role);
                        $acl->add_Resource("USERS");
                        //Доступ к спискам пользователей
                        $acl->add_access("1");
                        $access = array();
                        $access['allow'] = $acl->allow();
                        if($access['allow'] == true){
                            //Права на создание пользователей
                            $acl->add_access("2");
                            $access['allow_write'] = $acl->allow();
                            //Права на редактирование пользователей
                            $acl->add_access("3");
                            $access['allow_edit'] = $acl->allow();
                            //Права на отключение пользователей
                            $acl->add_access("4");
                            $access['allow_off'] = $acl->allow();
                            //Права на удаление пользователей
                            $acl->add_access("5");
                            $access['allow_delete'] = $acl->allow();
                            //Особые права
                            $acl->add_access("6");
                            $access['allow_super'] = $acl->allow();
                            $this->access = $access;

                            $this->users = ORM::factory()->SetType("assoc")->Select("users.id, users.username, users.real_name, users.email, users.activ, groups.cpanel, groups.role, acl.Rights")->Where(array("users.role"=>"groups.id","groups.id"=>"acl.Role","acl.Modul"=>"USERS"))->OrderBy("users.role, users.id")->crossjoin("users,groups,acl")->find_all();

                   }else{
				header("location: /admin.html");
				exit();
			}
                }else{
			header("location: /admin.html");
			exit();
		}
	}
	public function GroupsAction(){
		$this->title = "Групи";
		$auth = Df_Auth::read("id");
			if(!empty($auth)){
                        $acl = new Df_acl;
                        $acl->SetAclTableName("acl");
                        //Читаем ID групу пользователя
                        $role = Df_Auth::read("role");
                        $acl->addRole($role);
                        $acl->add_Resource("GROUPS");
                        //Доступ к группам пользователей
                        $acl->add_access("1");
                        $access = array();
                        $access['allow'] = $acl->allow();
                        if($access['allow'] == true){
                            //Права на создание груп
                            $acl->add_access("2");
                            $access['allow_write'] = $acl->allow();
                            //Права на редактирование груп
                            $acl->add_access("3");
                            $access['allow_edit'] = $acl->allow();
                            //Права на удаление груп
                            $acl->add_access("5");
                            $access['allow_delete'] = $acl->allow();
                            //Особые права
                            $acl->add_access("6");
                            $access['allow_super'] = $acl->allow();
                            $this->access = $access;
				$this->groups = ORM::factory()->SetType("assoc")->Select("groups.id, groups.role, groups.cpanel, acl.Rights")->Where(array("groups.id"=>"acl.Role", "acl.Modul"=>"GROUPS"))->OrderBy("groups.id","ASC")->crossjoin('groups, acl')->find_all();

                    }
                        }else{
				header("location: /admin.html");
				exit();
			}
	}
	public function AdduserAction(){
		$this->title = "Додати користувача";
		$auth = Df_Auth::read("id");
			if(!empty($auth)){
                             $acl = new Df_acl;
                             $acl->SetAclTableName("acl");
                            //Читаем ID групу пользователя
                            $role = Df_Auth::read("role");
                            $acl->addRole($role);
                            $acl->add_Resource("USERS");
                            //Права на создание пользователей
                            $acl->add_access("2");
                            if($acl->allow() == true){
					$this->groups = ORM::factory('groups')->find_all();
                                        require_once(APPLICATION_PATH."/Models/User.php");
					$this->status = User::Add();
                            }
			}
	}
         public function UsereditAction(){
            $auth = Df_Auth::read("id");

                 if(!empty($auth)){
                      $acl = new Df_acl;
                      $acl->SetAclTableName("acl");
                      //Читаем ID групу пользователя
                      $role = Df_Auth::read("role");
                      $acl->addRole($role);
                      $acl->add_Resource("USERS");
                      //Права на редактирование груп
                      $acl->add_access("3");
                          if($acl->allow() == true){
                             $this->groups = ORM::factory('groups')->find_all();
                             require_once(APPLICATION_PATH."/Models/User.php");

                                    $result = User::Edit();
                                    $this->access = $result["access"];
                                    $this->status = $result["status"];
                                    $this->data = $result["data"];
                                    $this->title = $result["title"];
                          }
                 }else{
				header("location: /admin.html");
				exit();
			}
         }
	public function AddgroupAction(){
		$this->title = "Додати групу";
		$auth = Df_Auth::read("id");

		if(!empty($auth)){
                        $acl = new Df_acl;
                        $acl->SetAclTableName("acl");
                        //Читаем ID групу пользователя
                        $role = Df_Auth::read("role");
                        $acl->addRole($role);
                        $acl->add_Resource("GROUPS");
                            //Права на создание груп
                            $acl->add_access("2");
                            $access['allow_write'] = $acl->allow();

                            if($access['allow_write'] == true){
                                //Особые права
                                $acl->add_access("6");
                                $access['allow_super'] = $acl->allow();
                                $this->access = $access;
                                
                                    require_once(APPLICATION_PATH."/Models/Group.php");
                                    $result = Group::Add();
                                    $this->status = $result['status'];
                                    $this->result = $result['result'];
                            }else{
                                $this->status = array('content'=>"Доступ заборонено!",'color'=>"red");
                                $this->result = NULL;
                            }
			}else{
				header("location: /admin.html");
				exit();
			}
        }

       public function GroupeditAction(){
		   $auth = Df_Auth::read("id");
			if(!empty($auth)){
                        $acl = new Df_acl;
                        $acl->SetAclTableName("acl");
                        //Читаем ID групу пользователя
                        $role = Df_Auth::read("role");
                        $acl->addRole($role);
                        $acl->add_Resource("GROUPS");
                        //Права на редактирование груп
                            $acl->add_access("3");
                if($acl->allow() == true){
				   require_once(APPLICATION_PATH."/Models/Group.php");
						$result = Group::Edit();
						$this->status = $result['status'];
						$this->role = $result['role'];
						$this->title = $result["title"];
						$this->priv = $result["priv"];
				}
                
			}else{
				header("location: /admin.html");
				exit();
			}
	}
	public function CatalogAction(){
		$this->title = "Каталог товарів";
		$auth = Df_Auth::read("id");
		if(!empty($auth)){
            $array = array();
            $acl = new Df_acl;
            $acl->SetAclTableName("acl");
            //Читаем ID групу пользователя
            $role = Df_Auth::read("role");
            $acl->addRole($role);
            $acl->add_Resource("RAZDEL");
            //Доступ к спискам разделам
            $acl->add_access("1");
            $access = array();
            $access['allow'] = $acl->allow();
			//$access['allow'] = false;
              if($access['allow'] == true){
                //Права на создание разделов
                $acl->add_access("2");
                $access['allow_write'] = $acl->allow();
                //Права на редактирование разделов
                $acl->add_access("3");
                $access['allow_edit'] = $acl->allow();
                //Права на публикацию разделов
                $acl->add_access("4");
                $access['allow_off'] = $acl->allow();
				//$access['allow_off'] = false;
                //Права на удаление разделов
                $acl->add_access("5");
                $access['allow_delete'] = $acl->allow();
                //права на смену главной страницы
                $acl->add_access("6");
                $access['allow_super'] = $acl->allow();
                $this->access = $access;
                
                $request = getRequest::getInstance();
				(int)$cat = $request->getVar('cat', 'GET');
				(int)$sub = $request->getVar('sub', 'GET');
				
				$this->sub = 0;
				
				$array = array();
                $array[] = array('link'=>'admin','name'=>'Головна');
                $array[] = array('link'=>'admin/grouptovar','name'=>'Групи товарів');
				
                if((!empty($cat) && $cat!=0) && (!empty($sub) && $sub!=0)){
					$this->sub = $sub;
					$this->cat = $cat;
					//$this->data = 
					#$this->goods = ORM::factory('goods')->SetType('assoc')->Select('id,name,url,sort,small')->Where(array('cat'=>$id))->find_all();
					$this->goods = ORM::factory()->SetType('assoc')->prepare("SELECT goods.id, goods.name, goods.url, goods.sort, goods.small, CetegoryTovar.url as `subcat`, GroupTovar.url as `group` FROM `goods`,`CetegoryTovar`, `GroupTovar` WHERE goods.cat='".$cat."' AND goods.sub='".$sub."' AND goods.Cat=CetegoryTovar.id AND CetegoryTovar.group = GroupTovar.id")->getResult();
					//echo"1";
				}elseif(!empty($cat) && $cat!=0){
					//echo"2";
					$this->cat = $cat;
					#$this->goods = ORM::factory('goods')->SetType('assoc')->Select('id,name,url,sort,small')->Where(array('cat'=>$id))->find_all();
					$this->goods = ORM::factory()->SetType('assoc')->prepare("SELECT goods.id, goods.name, goods.url, goods.sort, goods.small, GroupTovar.url as `group` FROM `goods`,`GroupTovar` WHERE goods.cat='".$cat."' AND '".$cat."' = GroupTovar.id")->getResult();
				}
				$array[] = array('link'=>'admin/catalog','name'=>$this->title,'param'=>$cat,'type'=>"cat");
               // echo"SUB : ".$this->sub."<br>";
				$this->link = LinkGen::Link($array, 'block', 'navig', 1);
			}
		}else{
				header("location: /admin.html");
				exit();
			}
	}
	public function GrouptovarAction(){
		$this->title = "Групи товарів";
		$auth = Df_Auth::read("id");
		if(!empty($auth)){
            $array = array();
            $acl = new Df_acl;
            $acl->SetAclTableName("acl");
            //Читаем ID групу пользователя
            $role = Df_Auth::read("role");
            $acl->addRole($role);
            $acl->add_Resource("RAZDEL");
            //Доступ к спискам разделам
            $acl->add_access("1");
            $access = array();
            $access['allow'] = $acl->allow();
			//$access['allow'] = false;
              if($access['allow'] == true){
                //Права на создание разделов
                $acl->add_access("2");
                $access['allow_write'] = $acl->allow();
                //Права на редактирование разделов
                $acl->add_access("3");
                $access['allow_edit'] = $acl->allow();
                //Права на публикацию разделов
                $acl->add_access("4");
                $access['allow_off'] = $acl->allow();
				//$access['allow_off'] = false;
                //Права на удаление разделов
                $acl->add_access("5");
                $access['allow_delete'] = $acl->allow();

                $this->access = $access;
                
                $this->catalog = ORM::factory('GroupTovar')->SetType('assoc')->Select('id,name,url')->find_all();
                
                $array = array();
                $array[] = array('link'=>'admin','name'=>'Головна');
                $array[] = array('link'=>'admin/grouptovar','name'=>$this->title);
                
				$this->link = LinkGen::Link($array, 'block', 'navig', 1);
			}
		}else{
				header("location: /admin.html");
				exit();
			}
	}
	public function AddgrAction(){
		$this->title = "Створити групу товарів";
		$auth = Df_Auth::read("id");
		$this->status = "";
		
		if(!empty($auth)){
            $array = array();
            $acl = new Df_acl;
            $acl->SetAclTableName("acl");
            //Читаем ID групу пользователя
            $role = Df_Auth::read("role");
            $acl->addRole($role);
            $acl->add_Resource("RAZDEL");
            //Доступ к спискам разделам
            $acl->add_access("1");
            $access = array();
            $access['allow'] = $acl->allow();
			//$access['allow'] = false;
              if($access['allow'] == true){
                //Права на создание разделов
                $acl->add_access("2");
                $access['allow_write'] = $acl->allow();
                				
                $this->access = $access;
                
                $array = array();
                $array[] = array('link'=>'admin','name'=>'Головна');
                $array[] = array('link'=>'admin/grouptovar','name'=>'Групи товарів');
                $array[] = array('link'=>'admin/addgr','name'=>$this->title);
                
				$this->link = LinkGen::Link($array, 'block', 'navig', 1);
				if($access['allow_write']==true){
					$request = getRequest::getInstance();
					if($request->isPost()){
						$name = $request->getVar('name', 'POST');
						$url = $request->getVar('url', 'POST');
						if(!empty($name)){
							if(empty($url)){
								LoadHelpers("Translit");
								$url = TranslitIt($name);
							}
							$orm = ORM::factory('GroupTovar');
							$orm->name = $name;
							$orm->url = $url;
							$orm->flush();
							if($orm->IsGood()){
								header("location: /admin/grouptovar.html");
							}else{
								$this->status = "Помилка";
							}
						}else{
							$this->status = "Ви не заповнили поле 'Назва'";
						}
					}
				}
			}
		}else{
				header("location: /admin.html");
				exit();
			}
	}
	public function EditgrAction(){
		$this->title = "Редагувати групу товарів";
		$auth = Df_Auth::read("id");
		$this->status = "";
		
		if(!empty($auth)){
            $array = array();
            $acl = new Df_acl;
            $acl->SetAclTableName("acl");
            //Читаем ID групу пользователя
            $role = Df_Auth::read("role");
            $acl->addRole($role);
            $acl->add_Resource("RAZDEL");
            //Доступ к спискам разделам
            $acl->add_access("1");
            $access = array();
            $access['allow'] = $acl->allow();
			//$access['allow'] = false;
              if($access['allow'] == true){
                //Права на создание группы товаров
                $acl->add_access("2");
                $access['allow_write'] = $acl->allow();
                //Права на редактирование группы товаров
                $acl->add_access("3");
                $access['allow_edit'] = $acl->allow();
				
                $this->access = $access;
                
                $array = array();
                $array[] = array('link'=>'admin','name'=>'Головна');
                $array[] = array('link'=>'admin/grouptovar','name'=>'Групи товарів');
                
				$this->link = LinkGen::Link($array, 'block', 'navig', 1);
				if($access['allow_edit']==true){
					$request = getRequest::getInstance();
					(int)$id = $request->getVar('id', 'GET');
					if(!empty($id) && $id!=0){
						$this->id = $id;
						$array[] = array('link'=>'admin/editgr','name'=>$this->title,'param'=>$id,'type'=>"id");
						
						if($request->isPost()){
							$name = $request->getVar('name', 'POST');
							$url = $request->getVar('url', 'POST');
							if(!empty($name)){
								if(empty($url)){
									LoadHelpers("Translit");
									$url = TranslitIt($name);
								}
								$orm = ORM::factory();
								
								$orm->prepare("UPDATE `GroupTovar` SET `name`='".$name."', `url`='".$url."' WHERE `id`='".$id."'")->execute();
								$this->info = array(array('name'=>$name,'url'=>$url));
								
								if($orm->IsGood()){
									header("location: /admin/grouptovar.html");
								}else{
									$this->status = "Помилка";
								}
							}else{
								$this->status = "Ви не заповнили поле 'Назва'";
							}
						}else{
							$this->info = ORM::factory('GroupTovar',$id)->SetType('assoc')->Select('name,url')->find_all();
						}
					}else{
						header("location: /admin/grouptovar.html");
					}
				}
			}
		}else{
				header("location: /admin.html");
				exit();
			}
	}
	public function SubcatAction(){
		$this->title = "Підкатегорії товарів";
		$auth = Df_Auth::read("id");
		if(!empty($auth)){
            $array = array();
            $acl = new Df_acl;
            $acl->SetAclTableName("acl");
            //Читаем ID групу пользователя
            $role = Df_Auth::read("role");
            $acl->addRole($role);
            $acl->add_Resource("RAZDEL");
            //Доступ к спискам разделам
            $acl->add_access("1");
            $access = array();
            $access['allow'] = $acl->allow();
			//$access['allow'] = false;
              if($access['allow'] == true){
                //Права на создание разделов
                $acl->add_access("2");
                $access['allow_write'] = $acl->allow();
                //Права на редактирование разделов
                $acl->add_access("3");
                $access['allow_edit'] = $acl->allow();
                //Права на публикацию разделов
                $acl->add_access("4");
                $access['allow_off'] = $acl->allow();
				//$access['allow_off'] = false;
                //Права на удаление разделов
                $acl->add_access("5");
                $access['allow_delete'] = $acl->allow();

                $this->access = $access;
               
                $request = getRequest::getInstance();
				(int)$id = $request->getVar('id', 'GET');
				
				$array = array();
                $array[] = array('link'=>'admin','name'=>'Головна');
                $array[] = array('link'=>'admin/grouptovar','name'=>'Групи товарів');
                
				
				if(!empty($id) && $id!=0){
					$this->id = $id;
					if(!empty($id)){
						#$array[] = array('link'=>'admin/subcat','name'=>$this->title,'param'=>$id,'type'=>"id");
						
						$this->catalog = ORM::factory('CetegoryTovar')->SetType('assoc')->Select('id,name,url')->Where('group',$id)->find_all();
						
						#$this->catalog = ORM::factory()->SetType('assoc')->prepare("SELECT CetegoryTovar.id,CetegoryTovar.name,CetegoryTovar.url,GroupTovar.url as `group` FROM `CetegoryTovar`,`GroupTovar` WHERE CetegoryTovar.group='".$id."' AND GroupTovar.id='".$id."'")->getResult();
						if(empty($this->catalog)){
							$this->goods = ORM::factory('goods')->SetType('assoc')->Select('id,name,url,sort,small')->Where(array('Cat'=>$id,'Sub'=>'0'))->find_all();
							$this->cat = $id;
							$array[] = array('link'=>'admin/subcat','name'=>'Каталог товарів','param'=>$id,'type'=>"id");
						}else{
							$array[] = array('link'=>'admin/subcat','name'=>$this->title,'param'=>$id,'type'=>"id");
						}
					}
				}else{
					header("location: /admin/grouptovar.html");
					exit();
				}
                
				$this->link = LinkGen::Link($array, 'block', 'navig', 1);
			}
		}else{
				header("location: /admin.html");
				exit();
			}
	}
	public function AddsubcatAction(){
		$this->title = "Створити підгрупу товарів";
		$auth = Df_Auth::read("id");
		$this->status = "";
		
		if(!empty($auth)){
            $array = array();
            $acl = new Df_acl;
            $acl->SetAclTableName("acl");
            //Читаем ID групу пользователя
            $role = Df_Auth::read("role");
            $acl->addRole($role);
            $acl->add_Resource("RAZDEL");
            //Доступ к спискам разделам
            $acl->add_access("1");
            $access = array();
            $access['allow'] = $acl->allow();
			//$access['allow'] = false;
              if($access['allow'] == true){
                //Права на создание разделов
                $acl->add_access("2");
                $access['allow_write'] = $acl->allow();
                				
                $this->access = $access;
                
                $array = array();
                $array[] = array('link'=>'admin','name'=>'Головна');
                $array[] = array('link'=>'admin/grouptovar','name'=>'Групи товарів');
                
				$this->link = LinkGen::Link($array, 'block', 'navig', 1);
				if($access['allow_write']==true){
					$request = getRequest::getInstance();
					(int)$id = $request->getVar('id', 'GET');
					if(!empty($id) && $id!=0){
						$this->id = $id;
						$array[] = array('link'=>'admin/addsubcat','name'=>$this->title,'param'=>$id,'type'=>"id");
						
						if($request->isPost()){
							$name = $request->getVar('name', 'POST');
							$url = $request->getVar('url', 'POST');
							if(!empty($name)){
								if(empty($url)){
									LoadHelpers("Translit");
									$url = TranslitIt($name);
								}
								$orm = ORM::factory('CetegoryTovar');
								$orm->name = $name;
								$orm->url = $url;
								$orm->group = $id;
								$orm->flush();
								if($orm->IsGood()){
									header("location: /admin/subcat.html?id=".$id);
								}else{
									$this->status = "Помилка";
								}
							}else{
								$this->status = "Ви не заповнили поле 'Назва'";
							}
						}
					}else{
						$ref = $request->Referrer();
						if(isset($ref['query'])){
							header("location: /".$ref['path']."?".$ref['query']);
						}else{
							header("location: /".$ref['path']);
						}
					}
				}
			}
		}else{
				header("location: /admin.html");
				exit();
			}
	}
	public function EditsubcatAction(){
		$this->title = "Редагування підгрупи товарів";
		$auth = Df_Auth::read("id");
		$this->status = "";
		
		if(!empty($auth)){
            $array = array();
            $acl = new Df_acl;
            $acl->SetAclTableName("acl");
            //Читаем ID групу пользователя
            $role = Df_Auth::read("role");
            $acl->addRole($role);
            $acl->add_Resource("RAZDEL");
            //Доступ к спискам разделам
            $acl->add_access("1");
            $access = array();
            $access['allow'] = $acl->allow();
			//$access['allow'] = false;
              if($access['allow'] == true){
                //Права на создание группы товаров
                $acl->add_access("2");
                $access['allow_write'] = $acl->allow();
                //Права на редактирование группы товаров
                $acl->add_access("3");
                $access['allow_edit'] = $acl->allow();
				
                $this->access = $access;
                
                $array = array();
                $array[] = array('link'=>'admin','name'=>'Головна');
                $array[] = array('link'=>'admin/grouptovar','name'=>'Групи товарів');
                
				$this->link = LinkGen::Link($array, 'block', 'navig', 1);
				if($access['allow_edit']==true){
					$request = getRequest::getInstance();
					(int)$id = $request->getVar('id', 'GET');
					if(!empty($id) && $id!=0){
						$this->id = $id;
						$array[] = array('link'=>'admin/editsubcat','name'=>$this->title,'param'=>$id,'type'=>"id");
						
						$this->group = ORM::factory('GroupTovar')->SetType('assoc')->Select('id,name')->find_all();
						
						if($request->isPost()){
							$name = $request->getVar('name', 'POST');
							$url = $request->getVar('url', 'POST');
							(int)$group = $request->getVar('group', 'POST');
							if(!empty($name)){
								if(empty($url)){
									LoadHelpers("Translit");
									$url = TranslitIt($name);
								}
								$orm = ORM::factory();
								
								$orm->prepare("UPDATE `CetegoryTovar` SET `name`='".$name."', `url`='".$url."', `group`='".$group."' WHERE `id`='".$id."'")->execute();
								$this->info = array(array('name'=>$name,'url'=>$url,'group'=>$group));
								
								if($orm->IsGood()){
									header("location: /admin/subcat.html?id=".$group);
								}else{
									$this->status = "Помилка";
								}
							}else{
								$this->status = "Ви не заповнили поле 'Назва'";
							}
						}else{
							$this->info = ORM::factory('CetegoryTovar',$id)->SetType('assoc')->Select('group,name,url')->find_all();
							/*echo "ID: ".$id."<br>";
							echo"<pre>";
							print_r($this->info);
							echo"</pre>";*/
						}
					}else{
						header("location: /admin/grouptovar.html");
					}
				}
			}
		}else{
				header("location: /admin.html");
				exit();
			}
	}
	public function AddtovarAction(){
		$this->title = "Додати товар";
		$auth = Df_Auth::read("id");
		LoadHelpers("Translit");
		
		if(!empty($auth)){
            $array = array();
            $acl = new Df_acl;
            $acl->SetAclTableName("acl");
            //Читаем ID групу пользователя
            $role = Df_Auth::read("role");
            $acl->addRole($role);
            $acl->add_Resource("RAZDEL");
            //Доступ
            $acl->add_access("1");
            $access = array();
            $access['allow'] = $acl->allow();
			//$access['allow'] = false;
              if($access['allow'] == true){
                //Права на создание
                $acl->add_access("2");
                $access['allow_write'] = $acl->allow();
                //Права на публикацию
                $acl->add_access("4");
                $access['allow_off'] = $acl->allow();

                $this->access = $access;
                                
                $request = getRequest::getInstance();
                (int)$Cat = $request->getVar('cat', 'GET');
                (int)$sub = $request->getVar('sub', 'GET');
				if(!empty($sub) && $sub!=0){
					$this->param = "cat=".$Cat."&sub=".$sub;
					$location = "/admin/catalog.html?id=".$Cat."&sub=".$sub;
				}else{
					$this->param = "cat=".$Cat;
					$location = "/admin/catalog.html?id=".$Cat;
					$sub = 0;
				}
				//echo"CAT : ".$Cat."<br>";
				//echo"SUB : ".$sub."<br>";
                
                if($request->isPost()){
					$this->layout = 'false';
					$orm = ORM::factory('goods');
					$name = $request->getVar('title', 'POST');
					$orm->name = $request->getVar('title', 'POST');
					$orm->materіal = $request->getVar('materіal', 'POST');
					$orm->color = $request->getVar('color', 'POST');
					$orm->term = $request->getVar('term', 'POST');
					
					$orm->keywords = $request->getVar('keywords', 'POST');
					$orm->description = $request->getVar('description', 'POST');
					$orm->descrip = htmlspecialchars($request->getVar('descrip', 'POST',1), ENT_QUOTES, 'UTF-8');
					$orm->body = htmlspecialchars($request->getVar('body', 'POST',1), ENT_QUOTES, 'UTF-8');
					
					$orm->sort = $request->getVar('order', 'POST');
					$orm->published = $request->getVar('published', 'POST');
					
					$url = TranslitIt($name);
					$c = $orm->prepare("SELECT count(`id`) as `count` FROM `goods` WHERE `url`='".$url."'")->getResult();
					
					//echo "URL: ".$url;
					//echo"<br>";
					//echo "C: ".$c[0]['count'];
									
					if($c[0]['count']!=0){
						$c = $c[0]['count'];
						$c = $c+1;
						$url = $url.$c;
						$c = $orm->prepare("SELECT count(`id`) as `count` FROM `goods` WHERE `url`='".$url."'")->getResult();
							if($c[0]['count']!=0){
								$c = $c[0]['count'];
								$c = $c+1;
								$url = $url.$c;
								//echo "URL: ".$url;
								//echo"<br>";
								//echo "C: ".$c[0]['count'];
							}
					}
					/*echo"<br>";
					echo "URL: ".$url;
					echo"<br>";
					echo "C: ".$c[0]['count'];
					echo"<br>";*/
					unset($c);
					$orm->url = $url;
					$orm->Cat = $Cat;
					$orm->Sub = $sub;
					$orm->flush();
					
					$tovar = $orm->return_id();
					if(isset($_FILES['tovar_images']) && !empty($_FILES['tovar_images']['name'])){
						require_once(PLUGINS_PATH."/Upload.php");
							$options = array(
								'image'=>array(
									'width'=>600,
										'prev'=>array(
											array('name'=>'prev','width'=>138),
                                            array('name'=>'home','height'=>306,'max'=>array('width'=>350)),
                                            array('name'=>'small','width'=>66)
										),
										'rand'=>1
								)
							);
							$inf = Upload('tovar_images', "goods", $options);

							$orm->prepare("UPDATE `goods` SET `image`='".$inf['name']."', `prev`='".$inf['prev']["0"]."', `home`='".$inf['prev']["1"]."', `small`='".$inf['prev']["2"]."' WHERE `id`='".$tovar."'")->execute();
					}
					header("location: ".$location);
				}
				
                
                $array = array();
                $array[] = array('link'=>'admin','name'=>'Головна');
                $array[] = array('link'=>'admin/addtovar','name'=>'Додати довар');
                
				$this->link = LinkGen::Link($array, 'block', 'navig', 1);
			}
		}else{
			header("location: /admin.html");
			exit();
		}
	}
	public function EdtAction(){
		$this->title = "Редагування опису товару";
		$this->status = "";
		$auth = Df_Auth::read("id");
			if(!empty($auth)){
                        $acl = new Df_acl;
                        $acl->SetAclTableName("acl");
                        //Читаем ID групу пользователя
                        $role = Df_Auth::read("role");
                        $acl->addRole($role);
                        $acl->add_Resource("RAZDEL");
                        //Права на редактирование товаров
                        $acl->add_access("3");
						$access['allow_edit'] = $acl->allow();
                        if($access['allow_edit'] == true){
                            $this->access = $access;
							$request = getRequest::getInstance();
							(int)$id = $request->getVar('id', 'GET');
							
							$this->id = $id;
							if(!empty($id)){
								if($request->isPost()){
									$orm = ORM::factory();
									$descrip = htmlspecialchars($request->getVar('descrip', 'POST', 1), ENT_QUOTES, 'UTF-8');
									if(empty($descrip)){
										$descrip="<p></p>";
									}
									$body = htmlspecialchars($request->getVar('body', 'POST', 1), ENT_QUOTES, 'UTF-8');
									if(empty($body)){
										$body="<p></p>";
									}
									$name = $request->getVar('name', 'POST');
									

									$orm->prepare("UPDATE `goods` SET `name`='".$name."', `body`='".$body."', `descrip`='".$descrip."' WHERE `id`='".$id."'")->execute();
									$this->info = array(array('name'=>$name,'body'=>$body,'descrip'=>$descrip));
									if($orm->IsGood()){
										$this->status = "Товар оновлено";
									}else{
										$this->status = "Помилка";
									}
								}else{
									$this->info = ORM::factory('goods',$id)->SetType('assoc')->Select('descrip,body,name')->find_all();
								}
							}

                        }
		}else{
                    header('location: /admin/logout.html');
		}
	}
	public function SdtAction(){
		$this->title = "Редагування інформації про товар";
		$this->status = "";
		$auth = Df_Auth::read("id");
		LoadHelpers("Translit");
			if(!empty($auth)){
                        $acl = new Df_acl;
                        $acl->SetAclTableName("acl");
                        //Читаем ID групу пользователя
                        $role = Df_Auth::read("role");
                        $acl->addRole($role);
                        $acl->add_Resource("RAZDEL");
                        //Права на редактирование товаров
                        $acl->add_access("3");
						$access['allow_edit'] = $acl->allow();
                        if($access['allow_edit'] == true){
                            $this->access = $access;
							$request = getRequest::getInstance();
							(int)$id = $request->getVar('id', 'GET');
							$this->id = $id;
							if(!empty($id)){
								if($request->isPost()){
									$orm = ORM::factory();
									$name = $request->getVar('name', 'POST');
									
									$materіal = $request->getVar('materіal', 'POST');
									$color = $request->getVar('color', 'POST');
									$term = $request->getVar('term', 'POST');
									
									$keywords = $request->getVar('keywords', 'POST');
									$description = $request->getVar('description', 'POST');

									(int)$sort = $request->getVar('sort', 'POST');
									
									$url = TranslitIt($name);
									$c = $orm->prepare("SELECT count(`id`) as `count` FROM `goods` WHERE `url`='".$url."'")->getResult();
									
									//echo "URL: ".$url;
									//echo"<br>";
									//echo "C: ".$c[0]['count'];
									
									if($c[0]['count']!=0){
										$c = $c[0]['count'];

										$c = $c+1;
										$url = $url.$c;
										
										$c = $orm->prepare("SELECT count(`id`) as `count` FROM `goods` WHERE `url`='".$url."'")->getResult();
											if($c[0]['count']!=0){
												$c = $c[0]['count'];

												$c = $c+1;
												$url = $url.$c;
												//echo "URL: ".$url;
												//echo"<br>";
												//echo "C: ".$c[0]['count'];
											}
									}
									
									unset($c);
									
									$orm->prepare("UPDATE `goods` SET `name`='".$name."', `url`='".$url."', `materіal`='".$materіal."', `color`='".$color."', `term`='".$term."', `sort`='".$sort."', `keywords`='".$keywords."', `description`='".$description."' WHERE `id`='".$id."'")->execute();
									
									unset($url);
									
									if($orm->IsGood()){
										$this->status = "Товар оновлено";
									}else{
										$this->status = "Помилка";
									}
									if(isset($_FILES['tovar_images']) && !empty($_FILES['tovar_images']['name'])){
										$this->images = ORM::factory('goods',$id)->SetType('assoc')->Select('home,image,small,prev')->find_all();
										
										if($this->images[0]['prev']!="notfound/prev_notfound.jpg"){
											$root = DOCUMENT_ROOT."/upload/goods";
											if(!is_dir($root.'/'.$this->images[0]['prev'])){
												unlink($root.'/'.$this->images[0]['prev']);
											}
											if(!is_dir($root.'/'.$this->images[0]['image'])){
												unlink($root.'/'.$this->images[0]['image']);
											}
											if(!is_dir($root.'/'.$this->images[0]['home'])){
												unlink($root.'/'.$this->images[0]['home']);
											}
											if(!is_dir($root.'/'.$this->images[0]['small'])){
												unlink($root.'/'.$this->images[0]['small']);
											}
										}
										require_once(PLUGINS_PATH."/Upload.php");
										$options = array(
											'image'=>array(
												'width'=>600,
													'prev'=>array(
														array('name'=>'prev','width'=>138),
														array('name'=>'home','height'=>306,'max'=>array('width'=>300)),
														array('name'=>'small','width'=>66)
													),
													'rand'=>1
											)
										);
										$inf = Upload('tovar_images', "goods", $options);
										
										$orm->prepare("UPDATE `goods` SET `image`='".$inf['name']."', `prev`='".$inf['prev']["0"]."', `home`='".$inf['prev']["1"]."', `small`='".$inf['prev']["2"]."' WHERE `id`='".$id."'")->execute();
										if($orm->IsGood()){
											$this->status = "Товар оновлено";
										}else{
											$this->status = "Помилка";
										}
									}
					
									$this->info = array(array('name'=>$name,'keywords'=>$keywords,'description'=>$description,'sort'=>$sort,'materіal'=>$materіal,'color'=>$color, 'term'=>$term));
								}else{
									$this->info = ORM::factory('goods',$id)->SetType('assoc')->Select('name,keywords,description,sort,materіal,color,term')->find_all();
								}
							}

                        }
		}else{
             header('location: /admin/logout.html');
		}
	}
	
	public function GalleryAction(){
		$this->title = "Фотоальбоми";
		$auth = Df_Auth::read("id");
		if(!empty($auth)){
            $array = array();
            $acl = new Df_acl;
            $acl->SetAclTableName("acl");
            //Читаем ID групу пользователя
            $role = Df_Auth::read("role");
            $acl->addRole($role);
            $acl->add_Resource("RAZDEL");
            //Доступ к спискам разделам
            $acl->add_access("1");
            $access = array();
            $access['allow'] = $acl->allow();
			//$access['allow'] = false;
              if($access['allow'] == true){
                //Права на создание разделов
                $acl->add_access("2");
                $access['allow_write'] = $acl->allow();
                //Права на удаление разделов
                $acl->add_access("5");
                $access['allow_delete'] = $acl->allow();

                $this->access = $access;
                
                $array = array();
                $array[] = array('link'=>'admin','name'=>'Головна');
                $array[] = array('link'=>'admin/gallery','name'=>'Фотоальбоми');

				$this->images = ORM::factory('album')->SetType('assoc')->Select('id,prev,desc')->find_all();
				$this->link = LinkGen::Link($array, 'block', 'navig', 1);
			}
		}else{
				header("location: /admin.html");
				exit();
			}
	}
	public function AddalbomAction(){
		$this->title = "Додати фотоальбом";
		$auth = Df_Auth::read("id");
		LoadHelpers("Translit");
		
		if(!empty($auth)){
            $array = array();
            $acl = new Df_acl;
            $acl->SetAclTableName("acl");
            //Читаем ID групу пользователя
            $role = Df_Auth::read("role");
            $acl->addRole($role);
            $acl->add_Resource("RAZDEL");
            //Доступ
            $acl->add_access("1");
            $access = array();
            $access['allow'] = $acl->allow();
			//$access['allow'] = false;
              if($access['allow'] == true){
                //Права на создание
                $acl->add_access("2");
                $access['allow_write'] = $acl->allow();
                //Права на публикацию
                $acl->add_access("4");
                $access['allow_off'] = $acl->allow();

                $this->access = $access;
                                
                $request = getRequest::getInstance();

                if($request->isPost()){
					$this->layout = 'false';
					$orm = ORM::factory('album');
					$name = $request->getVar('name', 'POST');
					
					$orm->sort = $request->getVar('order', 'POST');
					$orm->desc = $name;
					$url = TranslitIt($name);
					unset($name);
					$c = $orm->prepare("SELECT count(`id`) as `count` FROM `album` WHERE `url`='".$url."'")->getResult();
					
					//echo "URL: ".$url;
					//echo"<br>";
					//echo "C: ".$c[0]['count'];
									
					if($c[0]['count']!=0){
						$c = $c[0]['count'];
						$c = $c+1;
						$url = $url.$c;
						$c = $orm->prepare("SELECT count(`id`) as `count` FROM `album` WHERE `url`='".$url."'")->getResult();
							if($c[0]['count']!=0){
								$c = $c[0]['count'];
								$c = $c+1;
								$url = $url.$c;
								//echo "URL: ".$url;
								//echo"<br>";
								//echo "C: ".$c[0]['count'];
							}
					}
					//echo "URL: ".$url."<br>";
					//echo "NAME: ".$name."<br>";
					//echo "ORDER: ".$name;
					unset($c);
					$orm->url = $url;
					$orm->flush();
					
					$album = $orm->return_id();
					
					//echo"ID: ".$album."<br>";
					if(isset($_FILES['images']) && !empty($_FILES['images']['name'])){
						require_once(PLUGINS_PATH."/Upload.php");
							$options = array(
								'image'=>array(
									'width'=>250,
									'rand'=>1
								)
							);
							$inf = Upload('images', "gallery", $options);
							//echo "UPDATE `album` SET `perv`='".$inf['name']."' WHERE `id`='".$album."'";
							$orm->prepare("UPDATE `album` SET `prev`='".$inf['name']."' WHERE `id`='".$album."'")->execute();
					}
					header("location: /admin/gallery.html");
				}
				
                
                $array = array();
                $array[] = array('link'=>'admin','name'=>'Головна');
                $array[] = array('link'=>'admin/addtovar','name'=>'Додати довар');
                
				$this->link = LinkGen::Link($array, 'block', 'navig', 1);
			}
		}else{
			header("location: /admin.html");
			exit();
		}
	}
	public function ImagesAction(){
		$this->title = "Зображення";
		$auth = Df_Auth::read("id");
		if(!empty($auth)){
            $array = array();
            $acl = new Df_acl;
            $acl->SetAclTableName("acl");
            //Читаем ID групу пользователя
            $role = Df_Auth::read("role");
            $acl->addRole($role);
            $acl->add_Resource("RAZDEL");
            //Доступ к спискам разделам
            $acl->add_access("1");
            $access = array();
            $access['allow'] = $acl->allow();
			//$access['allow'] = false;
              if($access['allow'] == true){
                //Права на создание разделов
                $acl->add_access("2");
                $access['allow_write'] = $acl->allow();
                //Права на удаление разделов
                $acl->add_access("5");
                $access['allow_delete'] = $acl->allow();

                $this->access = $access;
                
                $array = array();
                $array[] = array('link'=>'admin','name'=>'Головна');
                $array[] = array('link'=>'admin/gallery','name'=>'Фотоальбоми');
                
                $request = getRequest::getInstance();
                (int)$id = $request->getVar('id', 'GET');
                $this->id = $id;
                if(!empty($id)){
					$this->images = ORM::factory('gallery')->SetType('assoc')->Select('id,prev')->Where('album',$id)->find_all();
					$array[] = array('link'=>'admin/images','name'=>'Зображення','param'=>$id,'type'=>"id");
				}
				$this->link = LinkGen::Link($array, 'block', 'navig', 1);
			}
		}else{
				header("location: /admin.html");
				exit();
			}
	}
	public function LoadimgAction(){
		$this->title = "Завантаження зображень";
		$auth = Df_Auth::read("id");
		if(!empty($auth)){
            $array = array();
            $acl = new Df_acl;
            $acl->SetAclTableName("acl");
            //Читаем ID групу пользователя
            $role = Df_Auth::read("role");
            $acl->addRole($role);
            $acl->add_Resource("RAZDEL");
            //Доступ к спискам разделам
            $acl->add_access("1");
            $access = array();
            $access['allow'] = $acl->allow();
              if($access['allow'] == true){
                //Права на создание разделов
                $acl->add_access("2");
                $access['allow_write'] = $acl->allow();
                if($access['allow_write']==true){
					$this->access = $access;
					
					$request = getRequest::getInstance();
					(int)$id = $request->getVar('id', 'GET');
					
					$this->id = $id;
					
					if($request->isPost()){
						
						$this->layout = "false";
						$name = $request->getVar('name', 'POST');
						
						if(!empty($id) && isset($_FILES['images']['name']) && !empty($_FILES['images']['name'])){
							
							require_once(PLUGINS_PATH."/Upload.php");
							$size = sizeof($_FILES['images']['name']);
							$options = array(
									'image'=>array(
										'width'=>700,
										'prev'=>array(
											array(
												'name'=>'prev',
												'width'=>250
											)
										),
										'rand'=>1
									)
							);
							
							$sql = array();
							$imgDir = DOCUMENT_ROOT."/upload/gallery/";
							
							for($i=0;$i<$size;$i++){
								$inf = MultiUpload('images',$i, $imgDir, $options);
								$sql[] = "('".$id."','".$inf['name']."','".$inf['prev']["0"]."', '".$name."')";
							}
							/*echo"<pre>";
							print_r($sql);
							echo"</pre>";*/
							if(!empty($sql)){
								//echo"<br>INSERT<br>";
								ORM::factory()->prepare("INSERT INTO `gallery`(`album`,`full`,`prev`,`descrip`) VALUES".implode(',', $sql))->execute();
							}
							header('location: /admin/images.html?id='.$id);
					
							//ORM::factory('gallery')->SetType('assoc')->Select('id,medi,folder')->Where('goods',$id)->find_all();
						}
					}
				}
			}
		}else{
			header("location: /admin.html");
			exit();
		}
	}
	public function ImagestovAction(){
		$this->title = "Зображення";
		$auth = Df_Auth::read("id");
		if(!empty($auth)){
            $array = array();
            $acl = new Df_acl;
            $acl->SetAclTableName("acl");
            //Читаем ID групу пользователя
            $role = Df_Auth::read("role");
            $acl->addRole($role);
            $acl->add_Resource("RAZDEL");
            //Доступ к спискам разделам
            $acl->add_access("1");
            $access = array();
            $access['allow'] = $acl->allow();
			//$access['allow'] = false;
              if($access['allow'] == true){
                //Права на создание разделов
                $acl->add_access("2");
                $access['allow_write'] = $acl->allow();
                //Права на удаление разделов
                $acl->add_access("5");
                $access['allow_delete'] = $acl->allow();

                $this->access = $access;
                
                $array = array();
                $array[] = array('link'=>'admin','name'=>'Головна');
                $array[] = array('link'=>'admin/grouptovar','name'=>'Групи товарів');
                
                $request = getRequest::getInstance();
                (int)$id = $request->getVar('id', 'GET');
                $this->id = $id;
                if(!empty($id)){
					$this->images = ORM::factory('gallery_tov')->SetType('assoc')->Select('id,medi')->Where('goods',$id)->find_all();
					$this->tovar = ORM::factory('goods')->SetType('assoc')->Select('id,name,Cat')->Where('id',$id)->find_all();
					$array[] = array('link'=>'admin/catalog','name'=>'Каталог товарів','param'=>$this->tovar[0]['Cat'],'type'=>"id");
					$array[] = array('link'=>'admin/images','name'=>$this->tovar[0]['name'],'param'=>$this->tovar[0]['id'],'type'=>"id");
				}
				$this->link = LinkGen::Link($array, 'block', 'navig', 1);
			}
		}else{
				header("location: /admin.html");
				exit();
			}
	}
	public function LoadimgtovAction(){
		$this->title = "Завантаження зображень";
		$auth = Df_Auth::read("id");
		if(!empty($auth)){
            $array = array();
            $acl = new Df_acl;
            $acl->SetAclTableName("acl");
            //Читаем ID групу пользователя
            $role = Df_Auth::read("role");
            $acl->addRole($role);
            $acl->add_Resource("RAZDEL");
            //Доступ к спискам разделам
            $acl->add_access("1");
            $access = array();
            $access['allow'] = $acl->allow();
              if($access['allow'] == true){
                //Права на создание разделов
                $acl->add_access("2");
                $access['allow_write'] = $acl->allow();
                if($access['allow_write']==true){
					$this->access = $access;
					
					$request = getRequest::getInstance();
					(int)$id = $request->getVar('id', 'GET');
					$this->id = $id;
					
					if($request->isPost()){
						$this->layout = "false";
						
						if(!empty($id) && isset($_FILES['images']['name']) && !empty($_FILES['images']['name'])){
							$albom = ORM::factory('folders')->SetType('assoc')->Where('goods',$id)->name;
							if(empty($albom)){
								$rand = date('YmdHis').mt_rand(100,1000);
								$albom = md5($rand);
								//echo"<br>ALBOM : ".$albom."<br>";
								@mkdir(DOCUMENT_ROOT."/upload/gallery_tov/".$albom, 0777);

								$orm = ORM::factory('folders');
								$orm->goods = $id;
								$orm->name = $albom;
								$orm->flush();
								unset($orm);
							}elseif(!file_exists(DOCUMENT_ROOT."/upload/gallery_tov/".$albom)){
								$rand = date('YmdHis').mt_rand(100,1000);
								$albom = md5($rand);
								//echo"<br>ALBOM : ".$albom."<br>";
								@mkdir(DOCUMENT_ROOT."/upload/gallery_tov/".$albom, 0777);
							}
							require_once(PLUGINS_PATH."/Upload.php");
							$size = sizeof($_FILES['images']['name']);
							$options = array(
									'image'=>array(
										'width'=>600,
											'prev'=>array(
												array('name'=>'small','width'=>70)
											),
										'rand'=>1
									)
							);
							
							$name = $request->getVar('name', 'POST');
							
							$sql = array();
							$imgDir = DOCUMENT_ROOT."/upload/gallery_tov/".$albom;
							
							for($i=0;$i<$size;$i++){
								$inf = MultiUpload('images',$i, $imgDir, $options);
								$sql[] = "('".$id."','".$albom.'/'.$inf['name']."','".$albom.'/'.$inf['prev']["0"]."','".$name."')";
							}
							
							if(!empty($sql)){
								/*echo"<pre>";
								print_r($sql);
								echo"</pre>";*/
								ORM::factory('gallery')->prepare("INSERT INTO `gallery_tov`(`goods`,`image`,`medi`,`name`) VALUES".implode(',', $sql))->execute();
							}
							header('location: /admin/imagestov.html?id='.$id);
					
							//ORM::factory('gallery')->SetType('assoc')->Select('id,medi,folder')->Where('goods',$id)->find_all();
						}
					}
				}
			}
		}else{
			header("location: /admin.html");
			exit();
		}
	}
}
